package cn.com.idmy.cloud.config;

import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring6.http.converter.FastJsonHttpMessageConverter;
import org.jetbrains.annotations.NotNull;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

public class GlobalRestTemplateConfig {
    @Bean
    @NotNull
    @LoadBalanced
    @ConditionalOnMissingBean({RestTemplate.class})
    public RestTemplate restTemplate(@NotNull ClientHttpRequestFactory factory) {
        var template = new RestTemplate(factory);
        var converters = template.getMessageConverters();
        converters.removeIf(converter -> converter instanceof StringHttpMessageConverter || converter instanceof GsonHttpMessageConverter || converter instanceof MappingJackson2HttpMessageConverter);
        converters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
        var converter = new FastJsonHttpMessageConverter();
        var config = new FastJsonConfig();
        //config.setWriterFeatures(DefaultConfig.jsonWriterFeatures);
        converter.setFastJsonConfig(config);
        converters.addFirst(converter);
        return template;
    }

    @Bean
    @NotNull
    @ConditionalOnMissingBean({ClientHttpRequestFactory.class})
    public ClientHttpRequestFactory requestFactory() {
        var factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(5000);
        factory.setReadTimeout(5000);
        return factory;
    }
}
